import os
import subprocess
from time import sleep

from loguru import logger


class MultiDevice:
    def _connect_appium(self,port_number):
        win_start = f"appium -a 127.0.0.1 -p {port_number} --session-override"
        subprocess.Popen(
            win_start,
            shell=True,
            stdout=True,
            stderr=subprocess.STDOUT
        )
        sleep(5)
    def _check_port(self,port_number):
        try:
            result = os.popen(f"netstat -ano | findstr :{port_number}").read().split("\n")[1]
            os.system(f"kill -9 {result.split()[4]}")
        except Exception as e:
            logger.info(f"端口{port_number}未被占用")

    def start_appium(self,port_number=4723):
        self._check_port(port_number)
        self._connect_appium(port_number)



